import { prePushOrder } from "@/api/client/documentManagement/advanceOrder";
import CommonHook from "@/hook/commonHook";
import FormHook from "@/hook/formHook";
import dayjs from "dayjs";
import { ref } from "vue";
import { useRouter } from "vue-router";

export default function OperationHook(state: Base.GeneraDataType) {
  const {
    // getChannelOpts,
    formState,
    formDataRef,
    waybillDataRef,
    drawerOpts,
    btnLoading,
    totalItemNumber,
    //  materialOpts,
    submitTipFlag,
    getAllWarehouseCodeOpts,
    getCoumsterChannelByCountry
  } = state;
  const { resetFields } = FormHook({ formState });
  const { dataDict } = CommonHook();
  const router = useRouter();
  const routeParams = ref<string>("");
  const changeCountryHandle = (val: string, row: Partial<ClientAdvanceOrder.WaybillInfo>) => {
    if (val) {
      // getCoumsterChannelByCountry(row);
      getAllWarehouseCodeOpts(row);
    }
    row.channelId = undefined;
    row.warehouseCode = undefined;
  };

  const changeChannelHandle = (val: string, row: Partial<ClientAdvanceOrder.WaybillInfo>) => {
    if (val) {
      getCoumsterChannelByCountry(row);
    }
    row.channelId = undefined;
  };

  const chooseAddressHandle = () => {
    drawerOpts.title = "选择取件地址";
    drawerOpts.width = "600px";
    drawerOpts.passData = formState;
    drawerOpts.component = "ChooseAddress";
    drawerOpts.visible = true;
  };
  const chooseWarehouseHandle = () => {
    drawerOpts.title = "送货仓库";
    drawerOpts.width = "900px";
    drawerOpts.passData = formState;
    drawerOpts.component = "ChooseWarehouse";
    drawerOpts.visible = true;
  };
  // 新增
  const addHandle = () => {
    formState.bizPreOrderShipmentReqDtoList.push({
      channelId: undefined,
      countryRegionId: undefined,
      itemNumber: undefined,
      remark: undefined,
      // productName: undefined,
      // purchaseInsurance: undefined,
      // materialQualityId: [],
      materialQualityName: undefined,
      warehouseCode: undefined
    });
  };
  const deleteHandle = (index: number) => {
    formState.bizPreOrderShipmentReqDtoList.splice(index, 1);
  };
  const submitHandle = () => {
    Promise.all([formDataRef.value.validate(), waybillDataRef.value.validate()]).then(() => {
      const { shippingMethod, expectedPickupTime, pickupAddressId, warehouseId, estimatedWeight, estimatedVolume, bizPreOrderShipmentReqDtoList, bizSysFilesReqDtoList } = formState;
      const params = {
        shippingMethod,
        expectedPickupTime: dayjs(expectedPickupTime).format("YYYY-MM-DD HH:mm:ss"),
        pickupAddressId,
        warehouseId,
        estimatedWeight,
        estimatedVolume,
        totalWaybillNumber: bizPreOrderShipmentReqDtoList.length || 0,
        totalItemNumber: totalItemNumber.value,
        bizPreOrderShipmentReqDtoList: bizPreOrderShipmentReqDtoList.map(
          ({
            channelId,
            countryRegionId,
            itemNumber,
            remark,
            warehouseCode,
            //  productName,
            // purchaseInsurance,
            // materialQualityId,
            materialQualityName
          }: any) => {
            const { code } = dataDict.value["WAREHOUSE_TYPE"].find((t: Base.GeneraDataType) => t.name === warehouseCode[0]) || {};
            return {
              channelId: channelId[1],
              channelAllocation: channelId[0],
              countryRegionId,
              itemNumber,
              remark,
              // productName,
              // purchaseInsurance: purchaseInsurance ? 1 : 0,
              // materialQualityId: materialQualityId.join(","),
              materialQualityName,
              warehouseCode: warehouseCode[1],
              addressType: code
            };
          }
        ),
        bizFileDetailReqDtoList: bizSysFilesReqDtoList.map((t: any) => {
          return {
            ...t,
            attr: null,
            hashInfo: null,
            metadata: null,
            thMetadata: null,
            thUserMetadata: null,
            userMetadata: null
          };
        })
      };
      btnLoading.value = true;
      prePushOrder(params)
        .then((res: any) => {
          const { code, data } = res;
          if (code === 200) {
            console.log(res);
            submitTipFlag.value = true;
            routeParams.value = data.waybillNumList;
            // message.success("下单成功!");
            // cancelHandle();
          }
        })
        .finally(() => (btnLoading.value = false));
    });
  };
  const cancelHandle = () => {
    resetFields();
    formDataRef.value.clearValidate();
    waybillDataRef.value.clearValidate();
  };
  // const changeMaterialHandle = (row: Base.GeneraDataType) => {
  //   const selectMaterial = materialOpts.value.filter((t: any) => {
  //     return row.materialQualityId.includes(t.id);
  //   });
  //   const nameLists = selectMaterial.map((t: any) => t.material);
  //   row.materialQualityName = nameLists.join(",");
  // };
  const drawerSubmitHandle = (state: any) => {
    if (drawerOpts.component === "ChooseAddress") {
      formState.pickupAddressId = state.id;
      formState.pickupAddress = state.address;
    } else if (drawerOpts.component === "ChooseWarehouse") {
      formState.warehouseId = state.id;
      formState.warehouseName = state.cnName;
    }
    drawerOpts.visible = false;
  };
  // 继续下单
  const keepOrderHandle = () => {
    submitTipFlag.value = false;
    cancelHandle();
  };
  // 下单成功查看预报
  const goPreOrderHandle = () => {
    submitTipFlag.value = false;
    cancelHandle();
    // router.push({ name: "ClientAdvanceManagement", state: { params: { preOrderNoList: routeParams.value } } });
    router.push({ name: "ClientWaybillManagement", state: { params: { waybillNumList: JSON.stringify(routeParams.value) } } });
  };
  return {
    addHandle,
    deleteHandle,
    changeCountryHandle,
    submitHandle,
    cancelHandle,
    chooseAddressHandle,
    drawerSubmitHandle,
    chooseWarehouseHandle,
    // changeMaterialHandle,
    keepOrderHandle,
    goPreOrderHandle,
    changeChannelHandle
  };
}
